#include"Game.h"

Game::Game()
{

}

Game::~Game()
{
    clean();
}

void Game::run()
{
    while(isRunning)
    {
        SDL_Event event;

        handleEvent(&event);
        update();
        render();
    
    }
}

void Game::init()
{
    if(SDL_Init(SDL_INIT_EVERYTHING!=0))
    {
        SDL_LogError(SDL_LOG_CATEGORY_ERROR,"SDL could not initialize! SDL_Error:%s\n",SDL_GetError());
        isRunning=false;
    }
    window = SDL_CreateWindow("SDL Tutorial",SDL_WINDOWPOS_CENTERED,SDL_WINDOWPOS_CENTERED,windowWidth,windowHeight,SDL_WINDOW_SHOWN);
    if(window == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_ERROR,"SDL could not initialize! SDL_Error:%s\n",SDL_GetError());
        isRunning=false;
    }

    renderer = SDL_CreateRenderer(window,-1,SDL_RENDERER_ACCELERATED);
    if(renderer == nullptr)
    {
        SDL_LogError(SDL_LOG_CATEGORY_ERROR,"SDL could not initialize! SDL_Error:%s\n",SDL_GetError());
        isRunning=false;
    }

    currentScene = new SceneMain();
}
void Game::clean()
{
    if(currentScene!=nullptr) 
    {
        currentScene->clean();
        delete currentScene;
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();

}
void Game::changeScene(Scene* scene)
{
    if(currentScene!=nullptr)
    {
        currentScene->clean();
        delete currentScene;

    }
    currentScene = scene;
    currentScene->init();

}

void Game::handleEvent(SDL_Event *event)
{
    while(SDL_PollEvent(event))
    {
        if(event->type == SDL_QUIT)
        {
            isRunning = false;
        }
        currentScene->handleEvent(event);
    }

}

void Game::update()
{
    currentScene->update();
}

void Game::render()
{    
    SDL_RenderClear(renderer);
    currentScene->render();

        //显示更新 
    SDL_RenderPresent(renderer);
}
